package com.ygo.feihua;

import android.content.*;
import android.os.*;
import android.support.v4.app.*;
import android.support.v7.app.*;
import android.support.v7.widget.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import cn.bmob.v3.datatype.*;
import cn.bmob.v3.exception.*;
import cn.bmob.v3.listener.*;
import com.ygo.feihua.*;
import com.ygo.feihua.BmobTable.*;
import com.ygo.feihua.Management.*;
import com.ygo.feihua.adapter.*;
import com.ygo.feihua.util.*;
import com.yuyh.library.imgsel.ui.*;
import java.util.*;

import android.support.v7.widget.Toolbar;
import com.ygo.feihua.fragment.*;
import android.util.*;

public class ShequFabu extends AppCompatActivity implements OnClickListener
{
	
	EditText ft_title,ft_neirong;
	private Button ft_qh;
	Gongju gj;
	DialogUtils du;
	private UserManagement um;
	private RecyclerView ft_rec;
	
	List<FatieMessage> data;
	private int mode=0;

	private FragmentFtJianyue fjy;

	private FragmentFtGaoji fgj;

	private FragmentManager fm;
	
	public static final int REQUEST_JIANYUE=0;
	public static final int REQUEST_GAOJI=1;
	private static final int FATIE_GAOJI = 1;
	private static final int FATIE_JIANYUE=0;
	
	private FatieTypeAdapter ftadp;
	
	public void closeMessage(){
		data.clear();
	}
	
	public void addMessage(FatieMessage ftm){
		data.add(ftm);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO: Implement this method
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shequ_fabu);
		gj=Gongju.getdx(this);
		um=UserManagement.getDx();
		du=DialogUtils.getdx(this);
		//CompressHelper.getDefault(this).compressToFile();
		
		ft_title=(EditText) findViewById(R.id.ft_title);
		ft_qh=(Button) findViewById(R.id.ft_qh);
		ft_rec=(RecyclerView) findViewById(R.id.ft_rec);
		gj.cshToolbar((Toolbar) findViewById(R.id.toolbar),"返回");

		data=new ArrayList<FatieMessage>();
		FatieMessage ftm=new FatieMessage();
		ftm.setImage_path("");
		ftm.setMessage("");
		data.add(ftm);
	
		List<TieType> ltt=new ArrayList<TieType>();
		TieType tt=new TieType();
		tt.setName("");
		tt.setIcon(null);
		ltt.add(tt);
		
		ftadp=new FatieTypeAdapter(this, ltt);

		LinearLayoutManager llm=new LinearLayoutManager(this);
		llm.setOrientation(LinearLayoutManager.HORIZONTAL);
		ft_rec.setLayoutManager(llm);
		ft_rec.setAdapter(ftadp);

		 fm = getSupportFragmentManager();
		 FragmentTransaction transaction = fm.beginTransaction();
		fjy = new FragmentFtJianyue();
		fgj=new FragmentFtGaoji();
		transaction.replace(R.id.ft_fragment, fjy);
		transaction.commit();
		
		ft_qh.setOnClickListener(new OnClickListener(){

				
				@Override
				public void onClick(View p1)
				{
					
					FragmentTransaction transaction = fm.beginTransaction();
					Fragment dqFragment = null;
					Fragment f3 = null;
					switch(mode){
						case 0:
							dqFragment=fjy;
							f3=fgj;
							mode=FATIE_GAOJI;
							
							break;
						case 1:
							dqFragment=fgj;
							f3=fjy;
							mode=FATIE_JIANYUE;
							break;
					
					}
				
					if (!f3.isAdded()) {
						// 先判断是否被add过
						transaction.hide(dqFragment).add(R.id.ft_fragment, f3).commit(); // 隐藏当前的fragment，add下一个到Activity中
					} else {

						transaction.hide(dqFragment).show(f3).commit(); // 隐藏当前的fragment，显示下一个
					}
					
					// TODO: Implement this method
				}
			});
		
	}


		
	
	
	@Override
	public void onClick(View p1)
	{
	
		// TODO: Implement this method
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// TODO: Implement this method
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK){
			if (data != null){
				ArrayList<String> photos = data.getStringArrayListExtra(ISListActivity.INTENT_RESULT);
				switch(requestCode){
					case REQUEST_JIANYUE:
						fjy.setImage(photos);
						break;
					case REQUEST_GAOJI:
						fgj.setImage(photos);
						break;
				}
			}
		}
	}
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// TODO: Implement this method
		getMenuInflater().inflate(R.menu.menu_ft, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// TODO: Implement this method
		switch(item.getItemId()){
			case R.id.action_ft:
				
				ft();
				break;
		}


		return super.onOptionsItemSelected(item);
	}
	
	private void ft()
	{
		final String title=ft_title.getText().toString().trim();	
		final TieType tieType;
		List<TieType> tt=ftadp.getData();
		if(!tt.get(tt.size()-1).getName().equals("")){
			tieType=tt.get(tt.size()-1);
		}else{
			tieType=null;
		}
		
		switch(mode){
			case FATIE_JIANYUE:
				fjy.getMessage();
				break;
			case FATIE_GAOJI:
				fgj.getMessage();
				break;
		}
		
		boolean bb=false;
		for (FatieMessage fm:data)
		{
			if (!fm.getMessage().equals(""))
			{
				bb = true;
				break;
			}
		}

		if (title.equals("") || !bb||tieType==null){
			gj.show("标题或内容为空/未选择帖子分类");
		}else{
			if (title.length() > 20){
				gj.show("标题字数不能超过20个");
			}else{
				if (um.getUser().getLiaotian_qx() != 1){

					
					du.dialogj1(false,"", "发布中,请稍等");
					
					
					List<String> ls=new ArrayList<String>();

					for (FatieMessage fm:data)
					{
						if (!fm.getImage_path().equals(""))
						{
							ls.add(fm.getImage_path());
						}
					}
					final List<TieziMessage> ltm=new ArrayList<TieziMessage>();
					
					if (ls.size() == 0){
						for (FatieMessage fm:data)
						{
							if(!fm.getMessage().equals("")){
							TieziMessage tm=new TieziMessage();
							tm.setMessage(fm.getMessage());
							tm.setImage(null);
							ltm.add(tm);
							}
						}
						fb(title,ltm,tieType);
						
					}else{
						du.setToast("图片上传中");
						final String[] ss=new String[ls.size()];
						ls.toArray(ss);


						BmobFile.uploadBatch(ss, new UploadBatchListener() {

								@Override
								public void onSuccess(final List<BmobFile> files, List<String> urls)
								{
									
									//1、files-上传完成后的BmobFile集合，是为了方便大家对其上传后的数据进行操作，例如你可以将该文件保存到表中
									//2、urls-上传文件的完整url地址
									if (urls.size() == ss.length)
									{//如果数量相等，则代表文件全部上传完成
										du.setToast("帖子发布中");
										int i=0;
										for (FatieMessage fm:data)
										{
											if(!fm.getMessage().equals("")||!fm.getImage_path().equals("")){
											TieziMessage tm=new TieziMessage();
											tm.setMessage(fm.getMessage());
											if (fm.getImage_path().equals(""))
											{
												tm.setImage(null);
												if(!fm.getMessage().equals("")){
													ltm.add(tm);
												}
											}else{
												tm.setImage(files.get(i));
												i++;
												ltm.add(tm);
											}
											}
										}							
										fb(title,ltm,tieType);
										//do something
									}
								}

								@Override
								public void onError(int statuscode, String errormsg)
								{
									//ShowToast("错误码"+statuscode +",错误描述："+errormsg);
									du.dis();

									gj.show("上传失败,原因为" + errormsg);

								}

								@Override
								public void onProgress(int curIndex, int curPercent, int total, int totalPercent)
								{

									du.setToast(("图片上传中\n" + curPercent + "%" + "\n" + curIndex + "/" + total + "\n总进度:" + totalPercent + "%"));
									//1、curIndex--表示当前第几个文件正在上传
									//2、curPercent--表示当前上传文件的进度值（百分比）
									//3、total--表示总的上传文件数
									//4、totalPercent--表示总的上传进度（百分比）
								}
							});
					}
				}
			}
		}
	}
	
	
	public void fb(String title,List<TieziMessage> ltm,TieType type){
		Tiezi tie=new Tiezi();
		tie.settitle(title);
		tie.setMessage(ltm);
		tie.settiezuo(um.getUser());
		tie.setPls(0);
		tie.setneirong("");
		tie.setTie_type(type);
		tie.save(new SaveListener<String>(){

				@Override
				public void done(String p1, BmobException p2)
				{
					if (p2 == null)
					{
						gj.show("发布成功");
						du.dis();
						finish();
					
					}else{
						du.dis();
						gj.toastBmobException(ft_title,"发布失败",p2);
						
						//gj.show("发布失败" + p2);
					}
					// TODO: Implement this method
				}
			});
	}
	
}
